const Roter=require('koa-router');
const fs = require("fs");
const path = require("path");
//const koaBody = require("koa-body"); // npm i koa-body
const {koaBody} = require('koa-body');
const { format } = require("date-fns"); // npm i date-fns
const {excelUploadDir} =require("../app/errorhandle")

const { saveTemplate,getALLTp,getALLTpByID,delByID,uploadExcel,getexcelfiles,delexcelByID } =require('../controller/template.controller')
const {authToken } = require('../middleware/user.middleware')

const templateRouter = new Roter({
  prefix: '/template'
});

templateRouter.get('/', authToken,getALLTp)
templateRouter.get('/:id', authToken,getALLTpByID)
templateRouter.post('/add', authToken,saveTemplate)
templateRouter.delete('/:id', authToken,delByID)

templateRouter.post('/delexcel', authToken,delexcelByID)
//templateRouter.post('/upload',authToken,uploadExcel)

templateRouter.post('/getexcelfiles', authToken,getexcelfiles)
templateRouter.post("/upload",authToken,
                    koaBody({
                      multipart: true, // 支持多文件上传
                      formLimit:"10mb",
                      jsonLimit:"10mb",
                      encoding: "gzip", // 编码格式
                      formidable: {
                        uploadDir: excelUploadDir, // 设置文件上传目录
                        keepExtensions: true, // 保持文件的后缀
                        maxFieldsSize: 10 * 1024 * 1024, // 文件上传大小限制
                        onFileBegin: (name, file) => {
                          //console.log("upload:name",name)
                          //console.log("onFileBegin:",file)
                          // 无论是多文件还是单文件上传都会重复调用此函数
                          // 最终要保存到的文件夹目录
                          //const dirName = format(new Date(), "yyyyMMddhhmmss");
                          //const dir = path.join(__dirname, `public/upload/${dirName}`);
                          const dir = excelUploadDir;
                          //console.log(process.cwd());//process.cwd()获取node的工作目录
                          //console.log(dir);
                          // 检查文件夹是否存在如果不存在则新建文件夹
                          if (!fs.existsSync(dir)) {
                              fs.mkdirSync(dir);
                            }
                          // 文件名称去掉特殊字符但保留原始文件名称
                          //console.log('filename:',file.name)
                          const fileName = file.originalFilename
                            .replaceAll(" ", "_")
                            .replace(/[`~!@#$%^&*()|\-=?;:'",<>\{\}\\\/]/gi, "_");
                          file.originalFilename = fileName;
                          //file.newFilename=fileName
                          // 覆盖文件存放的完整路径(保留原始名称)
                          file.path = `${dir}/${fileName}`;
                          //console.log("file.path",file.path)
                        },
                        onError: (error) => {
                          //app.status = 400;
                          //log4js.error(error);
                          // 这里可以定义自己的返回内容
                          app.body = { 
                            success:false, //response成功标识
                            code:200,
                            message:error.message,
                            data:error.message
                          };
                          return;
                        },
                      },
                    }),
                    
                    uploadExcel)

module.exports = templateRouter;